package com.yfp.operation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.core.constant.CacheConstants;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.operation.domain.ActivitySignInsRules;
import com.yfp.operation.domain.MarCoupon;
import com.yfp.operation.domain.MarCouponPack;
import com.yfp.operation.domain.dto.ActivitySignInsRulesCreateReqDTO;
import com.yfp.operation.domain.dto.ActivitySignInsSearchRewardReqDTO;
import com.yfp.operation.enums.ActivitySignInsRewardTypeEnums;
import com.yfp.operation.mapper.ActivitySignInsRulesMapper;
import com.yfp.operation.service.ActivitySignInsRulesService;
import com.yfp.operation.service.MarCouponPackDetailsService;
import com.yfp.operation.service.MarCouponPackService;
import com.yfp.operation.service.MarCouponService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @description 针对表【activity_sign_ins_rules(打卡管理-打卡规则表)】的数据库操作Service实现
 * @createDate 2025-01-02 10:43:50
 */
@Slf4j
@Service
public class ActivitySignInsRulesServiceImpl extends ServiceImpl<ActivitySignInsRulesMapper, ActivitySignInsRules> implements ActivitySignInsRulesService {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    public RedisTemplate redisTemplate;
    @Resource
    private ActivitySignInsRulesMapper activitySignInsRulesMapper;
    @Resource
    private MarCouponService marCouponService;
    @Resource
    private MarCouponPackService marCouponPackService;
    @Resource
    private MarCouponPackDetailsService marCouponPackDetailsService;

    @Override
    public List<ActivitySignInsRules> searchList(ActivitySignInsSearchRewardReqDTO searchReqDTO) {
        return activitySignInsRulesMapper.searchList(searchReqDTO);
    }

    @Override
    public List<ActivitySignInsRules> listByActivitySignInsId(Long id) {
        return activitySignInsRulesMapper.listByActivitySignInsId(id);
    }

    @Override
    public void lockInventory(List<ActivitySignInsRulesCreateReqDTO> activitySignInsRulesList) {
        activitySignInsRulesList.forEach(item -> {
            if (CollUtil.contains(ActivitySignInsRewardTypeEnums.getMarCouponList(), item.getRewardType())) {
                this.lockInventoryMarCoupon(item.getRewardId(), item.getTotalInventory());
            } else if (CollUtil.contains(ActivitySignInsRewardTypeEnums.getMarCouponPackList(), item.getRewardType())) {
                RLock lock = redissonClient.getLock(CacheConstants.MINAPP_ORDER_PACK_CREATE_LOCK_KEY + item.getRewardId());
                Assert.isTrue(lock.tryLock(), "稍后重试");
                try {
                    MarCouponPack marCouponPack = marCouponPackService.getById(item.getRewardId());

                    if (marCouponPack.getSurplusCount() < item.getTotalInventory()) {
                        throw new ServiceException("新增失败，" + marCouponPack.getPackName() + "的剩余数量不足");
                    }

                    // List<MarCouponPackDetails> marCouponPackDetails = marCouponPackDetailsService.listByCouponPackId(marCouponPack.getId());
                    // // item.getDistributionQuantity() 礼包赠券数固定 1
                    // for (Long i = 0L; i < item.getDistributionQuantity(); i++) {
                    //
                    //     for (Long j = 0L; j < item.getTotalInventory(); j++) {
                    //         for (MarCouponPackDetails marCouponPackDetail : marCouponPackDetails) {
                    //             for (int k = 0; k < marCouponPackDetail.getCouponCount(); k++) {
                    //                 this.lockInventoryMarCoupon(marCouponPackDetail.getCouponId(), marCouponPackDetail.getCouponCount());
                    //             }
                    //         }
                    //     }
                    //
                    // }
                    // 修改礼包剩余数量
                    marCouponPackService.updateSurplusCount(marCouponPack.getId(), NumberUtil.sub(marCouponPack.getSurplusCount(), item.getTotalInventory()).intValue());
                } finally {
                    lock.unlock();
                }
            }
        });
    }

    private void lockInventoryMarCoupon(Long rewardId, Long totalInventory) {
        RLock lock = redissonClient.getLock(CacheConstants.MAR_COUPON_SURPLUSCOUNT_LOCK_KEY + rewardId);
        Assert.isTrue(lock.tryLock(), "稍后重试");
        try {
            MarCoupon marCoupon = marCouponService.selectById(rewardId);

            if (marCoupon.getSurplusCount() < totalInventory) {
                throw new ServiceException("新增失败，" + marCoupon.getCouponName() + "的剩余数量不足");
            }
            // 修改优惠券剩余数量
            marCouponService.updateSurplusCount(marCoupon.getId(), NumberUtil.sub(marCoupon.getSurplusCount(), totalInventory).intValue());
        } finally {
            lock.unlock();
        }
    }
}




